// 门店运营监控模块
const { message } = window.antd;
const dayjs = window.dayjs;

// 生成模拟数据
function generateMockData() {
    const now = dayjs().toDate();
    const hours = now.getHours();
    
    // 基于时段生成订单量基准值
    const baseOrderCount = hours >= 11 && hours <= 13 ? 200 : // 午餐高峰
                          hours >= 17 && hours <= 19 ? 180 : // 晚餐高峰
                          80; // 平时
    
    // 添加随机波动
    const orderCount = Math.floor(baseOrderCount * (0.8 + Math.random() * 0.4));
    const avgOrderValue = 25 + Math.random() * 10;
    const revenue = orderCount * avgOrderValue;
    
    // 生成门店排名数据
    const storeRanking = {
        currentRank: Math.floor(Math.random() * 20) + 1,
        totalStores: 100,
        rankChange: Math.floor(Math.random() * 5) - 2
    };

    // 设置KPI预警阈值
    const thresholds = {
        orderCount: { min: baseOrderCount * 0.7 },
        revenue: { min: baseOrderCount * 25 * 0.7 },
        avgOrderValue: { min: 20, max: 40 },
        customerSatisfaction: { min: 4.0 }
    };

    // 检查指标是否超出阈值
    const checkThreshold = (value, threshold) => {
        if (threshold.min && value < threshold.min) return 'warning';
        if (threshold.max && value > threshold.max) return 'warning';
        return 'normal';
    };
    
    return {
        kpiData: {
            orderCount: {
                value: orderCount,
                trend: ((orderCount / baseOrderCount) - 1).toFixed(2),
                status: checkThreshold(orderCount, thresholds.orderCount)
            },
            revenue: {
                value: Math.floor(revenue),
                trend: ((revenue / (baseOrderCount * 25)) - 1).toFixed(2),
                status: checkThreshold(revenue, thresholds.revenue)
            },
            avgOrderValue: {
                value: avgOrderValue.toFixed(1),
                trend: ((avgOrderValue / 25) - 1).toFixed(2),
                status: checkThreshold(avgOrderValue, thresholds.avgOrderValue)
            },
            customerSatisfaction: {
                value: (4.2 + Math.random() * 0.6).toFixed(1),
                trend: (Math.random() * 0.1 - 0.05).toFixed(2),
                status: checkThreshold(parseFloat((4.2 + Math.random() * 0.6).toFixed(1)), thresholds.customerSatisfaction)
            }
        },
        storeRanking,
        storeStatus: {
            status: Math.random() > 0.9 ? 'warning' : 'normal',
            lastUpdate: now.toISOString()
        }
    };
}

// 生成24小时趋势数据
function generateTrendData() {
    const hours = Array.from({length: 24}, (_, i) => 
        i.toString().padStart(2, '0') + ':00'
    );
    
    const orderData = hours.map(hour => {
        const h = parseInt(hour);
        const base = h >= 11 && h <= 13 ? 200 :
                    h >= 17 && h <= 19 ? 180 : 80;
        return Math.floor(base * (0.8 + Math.random() * 0.4));
    });
    
    const revenueData = orderData.map(orders => 
        Math.floor(orders * (25 + Math.random() * 10))
    );
    
    return { hours, orderData, revenueData };
}

// 初始模拟数据
let mockData = generateMockData();
const trendData = generateTrendData();

// 初始化图表
function initCharts() {
    const orderTrendChart = echarts.init(document.getElementById('orderTrendChart'));
    const revenueTrendChart = echarts.init(document.getElementById('revenueTrendChart'));
    const avgOrderValueTrendChart = echarts.init(document.getElementById('avgOrderValueTrendChart'));

    // 配置订单趋势图表
    orderTrendChart.setOption({
        title: { text: '24小时订单量趋势' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
            type: 'category',
            data: trendData.hours,
            axisLabel: { interval: 3 }
        },
        yAxis: {
            type: 'value',
            name: '订单数量',
            nameTextStyle: { padding: [0, 0, 0, 30] }
        },
        series: [{
            name: '订单量',
            data: trendData.orderData,
            type: 'line',
            smooth: true,
            itemStyle: { color: '#1890ff' },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 0, y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(24,144,255,0.3)'
                    }, {
                        offset: 1, color: 'rgba(24,144,255,0.1)'
                    }]
                }
            }
        }]
    });

    // 配置营收趋势图表
    revenueTrendChart.setOption({
        title: { text: '24小时营收趋势' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
            type: 'category',
            data: trendData.hours,
            axisLabel: { interval: 3 }
        },
        yAxis: {
            type: 'value',
            name: '营收(元)',
            nameTextStyle: { padding: [0, 0, 0, 30] }
        },
        series: [{
            name: '营收',
            data: trendData.revenueData,
            type: 'line',
            smooth: true,
            itemStyle: { color: '#52c41a' },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 0, y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(82,196,26,0.3)'
                    }, {
                        offset: 1, color: 'rgba(82,196,26,0.1)'
                    }]
                }
            }
        }]
    });

    // 配置客单价趋势图表
    avgOrderValueTrendChart.setOption({
        title: { text: '24小时客单价趋势' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
            type: 'category',
            data: trendData.hours,
            axisLabel: { interval: 3 }
        },
        yAxis: {
            type: 'value',
            name: '客单价(元)',
            nameTextStyle: { padding: [0, 0, 0, 30] }
        },
        series: [{
            name: '客单价',
            data: trendData.revenueData.map((revenue, index) => 
                (revenue / trendData.orderData[index]).toFixed(2)
            ),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#722ed1' },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0, y: 0, x2: 0, y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(114,46,209,0.3)'
                    }, {
                        offset: 1, color: 'rgba(114,46,209,0.1)'
                    }]
                }
            }
        }]
    });

    // 监听窗口大小变化，自适应调整图表大小
    window.addEventListener('resize', () => {
        orderTrendChart.resize();
        revenueTrendChart.resize();
        avgOrderValueTrendChart.resize();
    });
}

// 更新KPI卡片数据
function updateKPICards(data) {
    const { kpiData, storeRanking } = data;
    Object.entries(kpiData).forEach(([key, value]) => {
        const card = document.querySelector(`#${key}Card`);
        if (card) {
            const valueElement = card.querySelector('.kpi-card-value');
            const trendElement = card.querySelector('.kpi-card-trend');
            
            // 更新数值
            valueElement.textContent = formatValue(key, value.value);
            
            // 更新趋势和状态
            const trendClass = value.trend > 0 ? 'trend-up' : 'trend-down';
            const trendText = `${Math.abs(value.trend * 100).toFixed(1)}%`;
            const statusClass = `status-${value.status}`;
            trendElement.innerHTML = `
                <span class="${trendClass} ${statusClass}">
                    ${value.trend > 0 ? '↑' : '↓'} ${trendText}
                    ${value.status === 'warning' ? '<i class="warning-icon">⚠️</i>' : ''}
                </span>
            `;
        }
    });

    // 更新门店排名信息
    const rankingElement = document.querySelector('.store-ranking');
    if (rankingElement) {
        const rankChangeIcon = storeRanking.rankChange > 0 ? '↑' : 
                             storeRanking.rankChange < 0 ? '↓' : '=';
        const rankChangeClass = storeRanking.rankChange > 0 ? 'rank-up' : 
                               storeRanking.rankChange < 0 ? 'rank-down' : 'rank-same';
        rankingElement.innerHTML = `
            <div class="ranking-value">${storeRanking.currentRank}/${storeRanking.totalStores}</div>
            <div class="ranking-change ${rankChangeClass}">
                ${rankChangeIcon} ${Math.abs(storeRanking.rankChange)}
            </div>
        `;
    }
}


// 更新门店状态
function updateStoreStatus(data) {
    const { status } = data.storeStatus;
    const statusDot = document.querySelector('.status-dot');
    if (statusDot) {
        statusDot.className = `status-dot status-${status}`;
    }
}

// 格式化数值显示
function formatValue(key, value) {
    // 确保value是数字类型
    const numValue = Number(value);
    switch(key) {
        case 'revenue':
            return `¥${numValue.toLocaleString()}`;
        case 'avgOrderValue':
            return `¥${numValue.toFixed(1)}`;
        case 'customerSatisfaction':
            return numValue.toFixed(1);
        default:
            return numValue.toLocaleString();
    }
}

// 初始化监控面板
export function initStoreMonitor() {
    try {
        // 创建图表容器
        const contentWrapper = document.querySelector('.content-wrapper');
        if (!contentWrapper) {
            throw new Error('找不到内容容器元素');
        }

        // 确保图表容器存在
        const storeMonitor = document.createElement('div');
        storeMonitor.className = 'store-monitor';
        storeMonitor.innerHTML = `
            <div class="monitor-header">
                <h2 class="monitor-title">门店运营监控</h2>
                <div class="monitor-filters">
                    <div class="store-status">
                        <span class="status-dot status-normal"></span>
                        <span>运营状态正常</span>
                    </div>
                </div>
            </div>

            <div class="kpi-cards">
                <div class="kpi-card" id="orderCountCard">
                    <div class="kpi-card-title">今日订单量</div>
                    <div class="kpi-card-value">0</div>
                    <div class="kpi-card-trend"></div>
                </div>
                <div class="kpi-card" id="revenueCard">
                    <div class="kpi-card-title">今日营收</div>
                    <div class="kpi-card-value">¥0</div>
                    <div class="kpi-card-trend"></div>
                </div>
                <div class="kpi-card" id="avgOrderValueCard">
                    <div class="kpi-card-title">客单价</div>
                    <div class="kpi-card-value">¥0</div>
                    <div class="kpi-card-trend"></div>
                </div>
                <div class="kpi-card" id="customerSatisfactionCard">
                    <div class="kpi-card-title">顾客满意度</div>
                    <div class="kpi-card-value">0</div>
                    <div class="kpi-card-trend"></div>
                </div>
                <div class="kpi-card ranking-card">
                    <div class="kpi-card-title">门店排名</div>
                    <div class="store-ranking"></div>
                </div>
            </div>

            <div class="charts-container">
                <div class="chart-card">
                    <div id="orderTrendChart" class="chart-container"></div>
                </div>
                <div class="chart-card">
                    <div id="revenueTrendChart" class="chart-container"></div>
                </div>
                <div class="chart-card">
                    <div id="avgOrderValueTrendChart" class="chart-container"></div>
                </div>
            </div>
        `;
        contentWrapper.innerHTML = '';
        contentWrapper.appendChild(storeMonitor);

        // 初始化图表
        initCharts();
        
        // 加载初始数据
        updateKPICards(mockData);
        updateStoreStatus(mockData);

        // 模拟实时数据更新
        setInterval(() => {
            // 生成新的模拟数据
            mockData = generateMockData();
            updateKPICards(mockData);
            updateStoreStatus(mockData);
        }, 30000); // 每30秒更新一次

    } catch (error) {
        console.error('初始化监控面板失败:', error);
        message.error('初始化监控面板失败，请刷新页面重试');
    }
}